package com.winit.openapi.gfs.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.command.GetByKeyCommand;
import com.winit.common.spi.context.CommandContext;
import com.winit.common.utils.Collections3;
import com.winit.gfs.spi.EbayInventoryConfigService;
import com.winit.gfs.spi.command.EbayInventoryConfigCommand;
import com.winit.gfs.spi.vo.EbayInventoryInfoVO;
import com.winit.gfs.spi.vo.EbayInventoryVO;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;

/**
 * 库存配置Controller
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * jianhua.huang 	1.0  		2015-8-11 	Created
 * 
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "/gfs/ebayInventory")
public class EbayInventoryConfigController extends BaseController {

	@Resource
	private EbayInventoryConfigService ebayInventoryConfigService;

	/**
	 * 保存或更新库存配置信息
	 * 
	 * @param requestMsg
	 * @param responseMsg
	 * @return
	 */
	@RequestMapping(value = "/saveOrUpdateConfig")
	public String saveOrUpdateConfig(@ModelAttribute RequestMsg requestMsg,
			@ModelAttribute ResponseMsg responseMsg) {
		Object obj = requestMsg.getData();
		if (obj instanceof JSONObject) {
			JSONObject json = (JSONObject) obj;
			// 校验参数
			validISPOrder(json);
			EbayInventoryVO inventoryVO = buildSaveDate(json);
			EbayInventoryConfigCommand command = new EbayInventoryConfigCommand();
			command.setInventoryVO(inventoryVO);
			command.setCtx(CommandContext.getContext());
			ebayInventoryConfigService.saveOrUpdateConfig(command);
		} else {
			throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
		}
		return SUCCESS;
	}

	/**
	 * 查询配置
	 * 
	 * @param requestMsg
	 * @param responseMsg
	 * @return
	 */
	@RequestMapping(value = "/findConfig")
	public String findConfig(@ModelAttribute RequestMsg requestMsg,
			@ModelAttribute ResponseMsg responseMsg) {
		GetByKeyCommand<Long> command = new GetByKeyCommand<Long>();
		CommandContext ctx = CommandContext.getContext();
		// 获取当前买家ID
		command.setCtx(ctx);
		command.setSearchKey(Long.parseLong(ctx.getUserId()));
		List<EbayInventoryVO> list = ebayInventoryConfigService.findConfig(command);
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("list", buildReturnList(list));
		responseMsg.setData(data);
		return SUCCESS;
	}

	/**
	 * 查询配置详情
	 * 
	 * @param requestMsg
	 * @param responseMsg
	 * @return
	 */
	@RequestMapping(value = "/findConfigInfo")
	public String findConfigInfo(@ModelAttribute RequestMsg requestMsg,
			@ModelAttribute ResponseMsg responseMsg) {
		Object obj = requestMsg.getData();
		if (obj instanceof JSONObject) {
			JSONObject json = (JSONObject) obj;
			// 校验参数
			ValidateUtil.validNotNull(json, "ebayInventoryID");
			ValidateUtil.validInteger(json, "ebayInventoryID", true);
			GetByKeyCommand<Long> command = new GetByKeyCommand<Long>();
			command.setSearchKey(json.getLong("ebayInventoryID"));
			List<EbayInventoryVO> list = ebayInventoryConfigService.findInfoConfig(command);
			responseMsg.setData(buildReturnInfoList(list));
		} else {
			throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
		}

		return SUCCESS;
	}

	/**
	 * 删除配置信息
	 * 
	 * @param requestMsg
	 * @param responseMsg
	 * @return
	 */
	@RequestMapping(value = "/deleteConfig")
	public String deleteConfig(@ModelAttribute RequestMsg requestMsg,
			@ModelAttribute ResponseMsg responseMsg) {
		Object obj = requestMsg.getData();
		if (obj instanceof JSONObject) {
			JSONObject json = (JSONObject) obj;
			// 校验参数
			ValidateUtil.validNotNull(json, "ebayInventoryID");
			ValidateUtil.validInteger(json, "ebayInventoryID", true);
			GetByKeyCommand<Long> command = new GetByKeyCommand<Long>();
			command.setSearchKey(json.getLong("ebayInventoryID"));
			command.setCtx(CommandContext.getContext());
			ebayInventoryConfigService.deleteConfig(command);
		} else {
			throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
		}

		return SUCCESS;
	}

	// 构建保存数据
	public EbayInventoryVO buildSaveDate(JSONObject json) {
		EbayInventoryVO config = new EbayInventoryVO();
		CommandContext ctx = CommandContext.getContext();
		// 设置bpartnerID
		config.setcBpartnerId(Long.parseLong(ctx.getUserId()));
		List<EbayInventoryInfoVO> listInfo = new ArrayList<EbayInventoryInfoVO>();
		EbayInventoryInfoVO infoConfig = null;
		if(json.containsKey("ebayUserid")){
			config.setEbayUserid(json.getString("ebayUserid"));
		}
		if(json.containsKey("ebaySite")){
			config.setEbaySite(json.getString("ebaySite"));
		}
		if(json.containsKey("warehouseCode")){
			config.setWarehouseCode(json.getString("warehouseCode"));
		}
		if(json.containsKey("warehouseName")){
			config.setWarehouseName(json.getString("warehouseName"));
			String country=json.getString("warehouseName").substring(0, 2);
			config.setCountryName(country);
		}
		if(json.containsKey("ebayInventoryID")){
			config.setEbayinventoryId(json.getLong("ebayInventoryID"));
		}
		
		if (json.containsKey("productList")) {
			JSONArray infoList = json.getJSONArray("productList");
			for (Object obj : infoList) {
				JSONObject info = (JSONObject) obj;
				infoConfig = new EbayInventoryInfoVO();
				if (info.containsKey("skuCode")) {
					infoConfig.setSkuCode(info.getString("skuCode"));
				}
				if (info.containsKey("specification")) {
					infoConfig.setSpecification(info.getString("specification"));
				}
				if (info.containsKey("enName")) {
					infoConfig.setEnName(info.getString("enName"));
				}
				if (info.containsKey("productName")) {
					infoConfig.setProductName(info.getString("productName"));
				}
				if (info.containsKey("availableInventory")) {
					infoConfig.setAvailableInventory(info.getLong("availableInventory"));
				}
				listInfo.add(infoConfig);
			}
			config.setListInfoVO(listInfo);
		}
		return config;
	}

	/**
	 * 构建返回数据
	 * 
	 * @param list
	 * @return
	 */
	public List<Map<String, Object>> buildReturnList(List<EbayInventoryVO> list) {
		List<Map<String, Object>> listMaps = new ArrayList<Map<String, Object>>();
		if (list==null) {
			return listMaps;
		}
		Map<String, Object> map = null;
		for (EbayInventoryVO inventoryVO : list) {
			map = new HashMap<String, Object>();
			map.put("ebayUserid", inventoryVO.getEbayUserid());
			map.put("country", inventoryVO.getCountryName());
			map.put("skuCode", inventoryVO.getSku());
			map.put("ebaySite", inventoryVO.getEbaySite());
			map.put("warehouseCode", inventoryVO.getWarehouseCode());
			map.put("warehouseName", inventoryVO.getWarehouseName());
			map.put("ebayInventoryID", inventoryVO.getEbayinventoryId());
			listMaps.add(map);
		}
		return listMaps;
	}

	/**
	 * 返回配置详情数据
	 * 
	 * @param list
	 * @return
	 */
	public Map<String, Object> buildReturnInfoList(
			List<EbayInventoryVO> list) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (list.size() <= 0) {
			return map;
		}
		map.put("ebayUserid", list.get(0).getEbayUserid());
		map.put("ebaySite", list.get(0).getEbaySite());
		map.put("warehouseCode", list.get(0).getWarehouseCode());
		map.put("ebayInventoryID", list.get(0).getEbayinventoryId());

		List<Map<String, Object>> listInfoVO = new ArrayList<Map<String, Object>>();
		Map<String, Object> mapInfo = null;
		if(Collections3.isEmpty(list.get(0).getListInfoVO())){
			return map;
		}
		for (EbayInventoryInfoVO infoVO : list.get(0).getListInfoVO()) {
			mapInfo = new HashMap<String, Object>();
			mapInfo.put("skuCode", infoVO.getSkuCode());
			mapInfo.put("specification", infoVO.getSpecification());
			mapInfo.put("productName", infoVO.getProductName());
			mapInfo.put("availableInventory", infoVO.getAvailableInventory());
			mapInfo.put("enName", infoVO.getEnName());
			listInfoVO.add(mapInfo);
		}
		map.put("productList", listInfoVO);
		return map;
	}

	/**
	 * 验证参数
	 * 
	 * @param json
	 */
	private void validISPOrder(JSONObject json) {
		ValidateUtil.valid(json, "ebayUserid", 50, true);
		ValidateUtil.valid(json, "ebaySite", 32, true);
		ValidateUtil.validNotNull(json, "warehouseCode");
		if (json.containsKey("productList")) {
			JSONArray infoList = json.getJSONArray("productList");
			for (Object obj : infoList) {
				JSONObject pack = (JSONObject) obj;
				ValidateUtil.valid(pack, "skuCode", 30, true);
				ValidateUtil.valid(pack, "productName", 200, true);
				ValidateUtil.validNotNull(pack, "availableInventory");
			}
		} 
	}

}
